package ftp;

import org.apache.ftpserver.DataConnectionConfiguration;
import org.apache.ftpserver.DataConnectionConfigurationFactory;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.Ftplet;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FtpServer类
 *
 * @author likai
 * @date 2018/9/17
 */
public class McFtpServer {
    public static void main(String[] args) {
        /**
         * ftp工厂
         */
        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory factory = new ListenerFactory();

        /**
         * 设置数据连接模式
         */
        DataConnectionConfigurationFactory dccFactory = new DataConnectionConfigurationFactory();
        //主动模式使用的端口
        dccFactory.setActiveLocalPort(8084);

        dccFactory.setPassiveIpCheck(true);
        dccFactory.setPassiveExternalAddress(FtpConfig.EXTERNAL_ADDRESS);
        dccFactory.setPassivePorts(FtpConfig.PASSIVE_PORT);
        DataConnectionConfiguration dcc = dccFactory.createDataConnectionConfiguration();


        factory.setDataConnectionConfiguration(dcc);
        factory.setPort(FtpConfig.PORT);
        serverFactory.addListener("default", factory.createListener());

        /**
         * 管理用户,并设置权限
         */
        UserManager userManagerFactory = serverFactory.getUserManager();
        BaseUser user = new BaseUser();
        user.setName(FtpConfig.FTP_NAME);
        user.setPassword(FtpConfig.PASSWORD);
        user.setHomeDirectory(FtpConfig.HOME_DIR);
        List<Authority> authorities = new ArrayList<>();
        authorities.add(new WritePermission());
        user.setAuthorities(authorities);
        try {
            userManagerFactory.save(user);
        } catch (FtpException e) {
            e.printStackTrace();
        }

        /**
         * 设置自定义的Ftplet
         */
        Map<String, Ftplet> m = new HashMap<>(2);
        /**
         * key的名字随意
         */
        m.put("MFtplet", new CustomFtplet());
        serverFactory.setFtplets(m);

        /**
         * 创建服务并启动
         */
        FtpServer server = serverFactory.createServer();
        try {
            server.start();
        } catch (FtpException ex) {
        }
    }
}
